package eerbaar.shared.internal.persist.save;

import java.util.ArrayList;
import java.util.List;

import eerbaar.shared.persist.ISaver;

public class Momento {

    private int index;

    private final List<ISaver<?>> list;

    public Momento(ISaver<?> start) {
        assert (start != null);
        if (start == null) {
            System.out.println("start is null");
        }

        this.list = new ArrayList<ISaver<?>>();
        this.list.add(start);
    }

    public Momento(ISaver<?>[] children) {
        assert (children != null);
        assert (children.length > 0);

        this.list = new ArrayList<ISaver<?>>();
        for (ISaver<?> saver : children) {
            if (saver == null) {
                System.out.println("saver == null");
            }
            assert (saver != null);
            this.list.add(saver);
        }
        // this.list.addAll(Arrays.asList(children));
    }

    public Momento(Momento momento) {
        assert (momento != null);

        this.list = new ArrayList<ISaver<?>>(momento.list);
        this.index = momento.index;
    }

    public ISaver<?> current() {
        assert (this.list.size() > 0);

        if (isAtEnd()) {
            return null;
        }

        ISaver<?> result = this.list.get(this.index);
        if (result == null) {
            System.out.println("result == null");
        }
        assert (result != null);

        return result;
    }

    public boolean isAtEnd() {

        return (this.index >= this.list.size());
    }

    public void next() {

        if (!isAtEnd()) {
            this.index++;
        }
    }

    @Override
    public String toString() {

        String s = "";
        s += "momento(";
        int i = 0;
        for (; i < this.list.size(); i++) {

            ISaver<?> saveable = this.list.get(i);

            if (i > 0) {
                s += ", ";
            }
            if (i == this.index) {
                s += "[";
            }
            s += saveable.getClass().getName();
            if (i == this.index) {
                s += "]";
            }
        }
        if (i == this.index) {
            s += "[]";
        }
        s += ")";

        return s;
    }

}
